import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';

import { queryBankList, saveBankCabinet, deleteBankCabinet } from './service';
import { fetchValidation } from '@/utils';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    saveCabinet: Effect;
    deleteCabinet: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'bankPayment',

  state: {
    dataInfo: {
      list: [],
      count: 0,
    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryBankList, payload);
      const data = fetchValidation(response);
      yield data &&
        put({
          type: 'save',
          payload: response.body,
        });
    },

    *saveCabinet({ payload }, { call, put }) {
      const response = yield call(saveBankCabinet, payload);
      return fetchValidation(response);
    },

    *deleteCabinet({ payload: { search, params } }, { call, put }) {
      const response = yield call(deleteBankCabinet, params);
      const dataInfo = fetchValidation(response);
      if (dataInfo) {
        message.success('删除成功');
        yield put({
          type: 'fetch',
          payload: search,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        dataInfo: action.payload,
      };
    },
  },
};

export default Model;
